package com.frxuexi.apps.view

import android.os.Environment
import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.apps.AppsIntent
import com.frxuexi.apps.AppsViewModel
import com.frxuexi.apps.entity.AppsData
import com.frxuexi.apps.entity.AppsEntity
import com.frxuexi.lib_base.BaseApp
import com.frxuexi.lib_base.IUiState
import com.frxuexi.lib_base.MyTitleBar
import com.frxuexi.lib_base.RequestType
import kotlinx.coroutines.launch
import java.io.File

@Composable
fun AppsPage(navHostController: NavHostController, vm: AppsViewModel = hiltViewModel()) {
    var list = remember {
        SnapshotStateList<AppsData>()
    }

    var isShowProgress by remember {
        mutableStateOf(false)
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.uiState.collect {
                when (it) {
                    is IUiState.onSuccess<*> -> {
                        if(it.type==RequestType.DOWNLOAD){
                            ToastUtils.showLong("下载成功")
                            isShowProgress=false
                        }else {
                            Log.i("===", it.data.toString())
                            list.addAll(it.data as Collection<AppsData>)
                        }
                    }

                    is IUiState.onError -> {
                        Log.i("===", it.msg)
                    }

                    else -> {}
                }
            }
        }

        vm.sendIntent(AppsIntent.getApps(mapOf(Pair("userId", 1), Pair("page", 1))))
    })

    Box(contentAlignment = Alignment.Center) {
        Column {
            MyTitleBar(navHostController = navHostController, title = "在线应用")
            list.forEach {
                Text(text = it.title, modifier = Modifier.padding(start = 10.dp))
                Spacer(modifier = Modifier.height(10.dp))
                LazyVerticalGrid(
                    verticalArrangement = Arrangement.spacedBy(10.dp),
                    columns = GridCells.Fixed(3),
                    content = {
                        items(it.appsList) { entity ->
                            AppsItem(entity,vm){
                                //点击下载显示开始进度框
                                isShowProgress=true
                            }
                        }
                    })
            }
        }

        if(isShowProgress) {
            CircularProgressIndicator(
                modifier = Modifier.width(64.dp),
                color = MaterialTheme.colorScheme.secondary,
                trackColor = MaterialTheme.colorScheme.surfaceVariant,
            )
        }
    }

}

@Composable
fun AppsItem(entity: AppsEntity,vm: AppsViewModel,onClick: () -> Unit) {
    var isShow by remember {
        mutableStateOf(false)
    }
    Column(horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier.clickable {
            isShow = true
        }) {
        AsyncImage(
            model = entity.appIcon, contentDescription = "",
            modifier = Modifier.size(40.dp)
        )
        Spacer(modifier = Modifier.height(5.dp))
        Text(text = entity.appName)
    }
    val path=BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

    if (isShow) {
        AlertDialog(onDismissRequest = { isShow = false },
            confirmButton = {
                Text(text = "下载", Modifier.clickable {
                    vm.sendIntent(AppsIntent.downloadApk(entity.apkUrl,File(path,entity.appName+".apk")))
                    isShow = false
                    onClick()
                })
            },
            dismissButton = { Text(text = "取消", Modifier.clickable { isShow = false }) },
            text = { Text(text = "确认下载${entity.appName}吗") },
            title = { Text(text = "下载提醒") })
    }
}